package cn.xd.security.captcha.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.util.IdUtil;
import cn.xd.common.constant.AuthConstant;
import cn.xd.security.captcha.CaptchaService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class CaptchaServiceImpl implements CaptchaService {
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 验证码值的有效期(单位:秒)，默认:120
     */
    @Value("${captcha.ttl:120}")
    long captchaValueTtl;

    @Override
    public Map<String, String> getLoginCaptcha() {
        //验证码内容长度
        int codeLength = 4;
        int lineLength = 10;
        //验证码宽度
        int width = 120;
        //验证码高度
        int height = 36;
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(width, height, codeLength, lineLength);
        // 缓存验证码至Redis
        String codeKey = IdUtil.simpleUUID();
        redisTemplate.opsForValue().set(String.format(AuthConstant.VERIFY_CODE_KEY_FORMAT, codeKey), circleCaptcha.getCode(), captchaValueTtl, TimeUnit.SECONDS);
        Map<String, String> result = new HashMap<>(2);
        result.put("verifyCodeKey", codeKey);
        result.put("verifyCodeImg", circleCaptcha.getImageBase64());
        return result;
    }
}
